<?php

namespace app\data\controller\merchant;

use app\data\controller\base\Publics;
use think\Db;
use think\Log;

/**
 * 活动参与
 * Class
 * @package app\data\controller\base
 */
class Cash
{

	use \app\common\traits\ToolTrait;
	/**
	 * 实例对象
	 * @var object
	 */
	protected static $instance;

	/**
	 * 表默认配置
	 * @var \app\data\constants\TabConstants::TAb_CONFIG
	 */
	protected $tabConfig = null;

	/**
	 * 翻页存储路径
	 * @var string
	 */
	protected $path = "./timer/page/merchant";

	/**
	 * 翻页文件存储配置
	 * @var string
	 */
	protected  $fileConfig = [
		"cash" => "cash_page.txt" 	//  新人注册交易达标
	];

	/**
	 * 翻页配置
	 * @var array
	 */
	protected $pageConfig = [
		"cash" 	=> ["page" 	=> 0, "total"	=> 0, "limit" => 10]
	];

	/**
	 * 构造
	 */
	public function __construct()
	{
		$this->tabConfig = Publics::instance()->tab();
	}

	/**
	 * 实例化
	 */
	public static function instance()
	{
		if (is_null(self::$instance)) {
			self::$instance = new static();
		}
		return self::$instance;
	}

	/**
	 * 临时存储
	 */
	public function temyStore()
	{
		$ids = $this->get_ids();
		if ($ids) {
			$data = [];
			foreach ($ids as $v) {
				$temp = [];
				$temp["uid"] = $v;
				array_push($data, $temp);
			}
			$check = Db::name($this->tabConfig->mer_cash_temy)->count();
			if (!$check) {
				$ret = Db::name($this->tabConfig->mer_cash_temy)->insertAll($data);
				if ($ret) {
					$file = $this->fileConfig["cash"];
					$pageConfig = $this->pageConfig["cash"];
					$this->create_directory($this->path, $file, $pageConfig);
					$totalPage = 0;
					$total = count($ids);
					if ($total) {
						$totalPage = ceil($total / $pageConfig['limit']);
					}
					$pageConfig["total"] = $totalPage;
					file_put_contents($this->path . '/' . $file, serialize($pageConfig));
				}
			}
		}
	}

	/**
	 * 返现计算
	 */
	public function cashCalc($uid)
	{
		if (!$uid) {
			return false;
		}

		$day = date("d", time());
		if ((int)$day == 5) {
			$userStatus = $this->checkUserStatus($uid);
			if ($userStatus) {
				$template = $this->_getCashTemplate($uid);
				if ($template) {
					$flag = true;
					$option = [];
					$option = ["uid" => $uid];
					$check = Db::name($this->tabConfig->mer_status)->where($option)->count();
					if (!$check) {
						$reg = strtotime(date("Y-m-d", $this->_user_jointime($option["uid"])));
						$option["reg_time"] = $reg;
						$id = Db::name($this->tabConfig->mer_status)->insertGetId($option);
						if (!$id) {
							$flag = false;
						}
					}
					if ($flag) {
						$this->cashbackLogicCalc($uid, $template);
					}
				}
			}
		}
		return false;
	}

	/**
	 * 逻辑计算
	 */
	private function cashbackLogicCalc($uid, $template)
	{
		$cashTime = strtotime(date("Y-m", strtotime("-1 month", time())));
		$find = Db::name($this->tabConfig->mer_status)->where("uid", $uid)->find();
		if ($find["status"] != 3) {
			$regTime = strtotime(date("Y-m", $find["reg_time"]));
			if ($regTime <= $cashTime) {
				$nums = 0;
				if ($find["status"] == 1) {
					if ($cashTime == $regTime) {
						$days = date("d", $find["reg_time"]);
						if ($days < $template['nums']) {
							$nums = bcsub((string)$template['nums'], (string)$days);
						} else {
							$nums = 1;
						}
					}
				} else {
					if ($find["status"] == 2) {
						$outTime = strtotime(date("Y-m", $find["out_time"]));
						if ($cashTime == $regTime || $cashTime == $outTime) {
							$nums = date("d", $find["out_time"]) - date("d", $find["reg_time"]);
						} else {
							$nums = date("d", $find["out_time"]);
						}
					}
				}
				$money = 100;
				if ($nums > 0) {
					$money = bcmul((string)$template["cashMoney"], (string) $nums);
				} else {
					$nums = $template["nums"];
				}
				$checkCash = Db::name($this->tabConfig->mer_cash_cords)->where("cash_time", $cashTime)->count();
				if (!$checkCash) {
					$option = [
						"uid" 			=> $uid,
						"date_type" 	=> 1,
						"nums"			=> $nums,
						"cashMoney" 	=> $money,
						"create_time"	=> time(),
						"cash_time"		=> $cashTime
					];
					$id = Db::name($this->tabConfig->mer_cash_cords)->insertGetId($option);
					if ($id) {
						if ($find["status"] == 2) {
							$update["status"] = 3;
							Db::name($this->tabConfig->mer_status)->where("id", $find["id"])->update($update);
						}
						$chgBalcOption = [
							"uid"		=> $uid,
							"typs"		=> "MER",
							"isChg" 	=> "1",
							"remark" 	=> "商户佣金返现",
							"chgAmt" 	=> $money,
						];
						\app\common\controller\Balance::instance()->changeOpera($chgBalcOption);
					}
				}
			}
		}
	}



	/**
	 * 获取用户返现计算信息
	 */
	private function getCashCalcCords($uid)
	{
		if (!$uid) {
			return false;
		}
		return Db::name($this->tabConfig->mer_cash_calc)->where("uid", $uid)->where("status", 1)->find();
	}

	/**
	 * 用户加入时间
	 */
	public function _user_jointime($id)
	{
		$ret = Db::name($this->tabConfig->user)->where("id", $id)->value("createtime");
		return $ret;
	}

	/**
	 * 商户状态
	 */
	public function checkUserStatus($id)
	{
		$return = false;
		$status = Db::name($this->tabConfig->user)->where("id", $id)->value("status");
		if ($status == 'normal') {
			$return = true;
		}
		return $return;
	}

	/**
	 * 获取参与记录
	 */
	public function _getCashTemplate($id)
	{
		if (!$id) {
			return false;
		}
		$table = $this->tabConfig->mer_cash;
		$template = Db::name($table)->where("status", 1)->column("mer_id");
		if ($template) {
			$where = ["mer_id" => 0];
			if (in_array($id, $template)) {
				$where["mer_id"] = $id;
			}
			$find = Db::name($table)->where($where)->field("id,mer_id,date_type,nums,cashMoney")->find();
			return $find;
		}
	}

	/**
	 * 创建文件
	 */
	public function create_directory($path, $file, $pageCon)
	{
		$isDir = $this->creDirectory($path);
		if ($isDir) {
			$file = $path . "/" .  $file;
			!file_exists($file) && file_put_contents($file, serialize($pageCon));
		}
	}

	/**
	 * 清空表
	 */
	public function clearTable()
	{
		Db::execute("TRUNCATE `fd_community`.`" . $this->tabConfig->prefix . $this->tabConfig->mer_cash_temy . "`");
	}

	/**
	 * 文件路径
	 */
	public function file_path($t)
	{
		return $this->path . "/" . $this->fileConfig[$t];
	}

	/**
	 * 获取参与ID 组
	 */
	public function get_ids()
	{
		$ret = Db::name($this->tabConfig->user)->where("is_typs", 1)->where("status", "normal")->column("id");
		return $ret;
	}
}
